package com.qbm.association.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.qbm.association.bean.ResultBean;
import com.qbm.association.config.Audience;
import com.qbm.association.util.JWTTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    private Audience audience;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {

        final String token = request.getHeader(JWTTokenUtil.AUTH_HEAD_KEY);
        System.err.println(token);
        if (null != token && !JWTTokenUtil.isExpiration(token, audience.getBase64Secret())) {
            return true;
        }
        if (HttpMethod.OPTIONS.toString().equals(request.getMethod())) {
            return true;
        }
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");
        JSONObject jsonObject = new JSONObject();
        ResultBean resultBean = ResultBean.overDue("登录过期,请重新登录");
        jsonObject.put("resultBean", resultBean);
        response.getOutputStream().write(jsonObject.toString().getBytes("UTF-8"));
        return false;
    }
}